package com.firexxx.study.server.asyncservlet.service;

import com.firexxx.study.performancetest.timeconsume.ConsumeTaskType;
import com.firexxx.study.performancetest.timeconsume.CpuTimeConsume;
import com.firexxx.study.performancetest.timeconsume.IoTimeConsume;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SettableListenableFuture;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/04/06 16:02
 */
@Service
@Slf4j
@EnableAsync
public class TestService {

    private CpuTimeConsume cpuTimeConsume = new CpuTimeConsume();
    private IoTimeConsume ioTimeConsume = new IoTimeConsume();

    public String sync(long delay, ConsumeTaskType consumeTaskType) throws InterruptedException {
        if (consumeTaskType == ConsumeTaskType.cpu) {
            cpuTimeConsume.setTime((int)delay);
            cpuTimeConsume.run();
        } else {
            ioTimeConsume.setTime((int)delay);
            ioTimeConsume.run();
        }

        log.info("service执行线程:" + Thread.currentThread().getName());

        return "sync:" + Thread.currentThread().getName();
    }

    @Async
    public ListenableFuture<String> async(long delay, ConsumeTaskType consumeTaskType) throws InterruptedException {
        if (consumeTaskType == ConsumeTaskType.cpu) {
            cpuTimeConsume.setTime((int)delay);
            cpuTimeConsume.run();
        } else {
            ioTimeConsume.setTime((int)delay);
            ioTimeConsume.run();
        }

        SettableListenableFuture<String> listenableFuture = new SettableListenableFuture<>();
        listenableFuture.set("async:" + Thread.currentThread().getName());

        log.info("service执行线程:" + Thread.currentThread().getName());

        return listenableFuture;
    }

}